package com.xxxx.server.task;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.xxxx.server.pojo.Employee;
import com.xxxx.server.pojo.MailConstants;
import com.xxxx.server.pojo.MailLog;
import com.xxxx.server.service.IEmployeeService;
import com.xxxx.server.service.IMailLogService;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
import java.util.List;

@Component
public class MailTask {
    @Autowired
    private IMailLogService mailLogService;
    @Autowired
    private IEmployeeService employeeService;
    @Autowired
    private RabbitTemplate rabbitTemplate;


    @Scheduled(cron = "0/100 * * * * ?")
    public void m(){
        List<MailLog> logList=mailLogService.list(new QueryWrapper<MailLog>().eq("status",0));
        for(MailLog mail : logList){

        }
    }








    @Scheduled(cron = "0/10 * * * * ?")
    public void mailTask(){
        List<MailLog> list  = mailLogService.list(new UpdateWrapper<MailLog>().eq("status",0));
    list.forEach(mailLog -> {
        //如果尝试次数大于等于3，则修改为2失败状态
        if (mailLog.getCount()>=3) {
            mailLogService.update(new UpdateWrapper<MailLog>().set("status", 2).
                    eq("msgId",mailLog.getMsgId()));
        }
        mailLogService.update(new UpdateWrapper<MailLog>().set("count",mailLog.getCount()+1).
                set("updateTime",LocalDateTime.now()).set("tryTime",LocalDateTime.now().
                plusMinutes(MailConstants.MSG_TIMEOUT)).eq("msgId",mailLog.getMsgId()));
        Employee employee =employeeService.getemployee(mailLog.getEid()).get(0);
        rabbitTemplate.convertAndSend(MailConstants.MAIL_EXCHANGE_NAME,MailConstants.MAIL_QUEUE_NAME,employee,
                new CorrelationData(mailLog.getMsgId()));
        });
    }
}
